package com.joysuch.wwyt.api.sync.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.dataaccess.OrientationDataSyncServiceImpl;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.api.sync.SyncResponse;
import com.joysuch.wwyt.api.sync.bean.BaseSyncContractorBean;
import com.joysuch.wwyt.api.sync.service.BaseSyncContractorService;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.repository.BpContractorDao;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class BaseSyncContractorServiceImpl implements BaseSyncContractorService {

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private BpContractorDao bpContractorDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BpDepartService departService;

    @Autowired
    private OrientationDataSyncServiceImpl orientationDataSyncService;


    @Override
    public ResultBean syncContractor() {
        log.debug("承包商列表同步Job 开始 ...");
        Set<String> bukrs = SyncConstants.unitCodeMap.keySet();
        List<String> msgList = new ArrayList<>();
        for(String companyCode: bukrs){
            try {
                ResultBean result = syncContractorByCompany(companyCode);
                msgList.add(result.getData().toString());
            }catch(Exception e){
                log.error("承包商列表同步出错： companyCode={}",companyCode,e);
            }
        }
        log.debug("承包商列表同步Job 结束 ...");
        return ResultBean.success(msgList);
    }

    @Override
    public ResultBean syncContractorByCompany(String companyCode) {
        BaseConfig config = baseConfigService.findConfig(SyncConstants.TENENT_ID_DEFAULT, companyCode, SyncConstants.BASE_CONFIG_CONTRACTOR_LIST_URL);
        if (config != null && StringUtils.isNotEmpty(config.getValue())) {
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            //set request body
            HttpEntity<String> requestBody = new HttpEntity<String>(companyCode, header);
            log.debug("承包商列表同步Job：url={}, param={}", config.getValue());

            SyncResponse response = restTemplate.postForObject(config.getValue(), requestBody, SyncResponse.class);
            if (response.getMsgcode().equals("0")) {
                if (response.getData() == null) {
                    log.debug("承包商列表同步Job： 获取数据列表为空， URL={}", config.getValue());
                    return ResultBean.success("承包商列表同步完成：  共同步0条记录；");
                }
                String data = JSONObject.toJSONString(response.getData());

                JSONObject content = JSONObject.parseObject(data);
                Integer count= processList(content.getString("content"), companyCode);


                return ResultBean.success("承包商列表同步结束： 共同步" + count.toString() + "条记录；" );
            } else {
                log.error("承包商列表同步Job： 接口数据获取失败： {}", response);
                return ResultBean.success("承包商列表同步失败：  接口数据获取失败；");
            }
        }
        return ResultBean.success("承包商列表同步失败：  同步接口未配置；");

    }


    // 人员信息处理
    private Integer processList (String content, String companyCode){
        if(content == null){
            return 0;
        }
        List<BaseSyncContractorBean> list = JSONArray.parseArray(content,BaseSyncContractorBean.class );
        log.debug(".... 承包商同步Job： 共查询列表 list:{} ....", list.size());

        List<BpContractor> conList = new ArrayList<>();
        int count = 0;
       String flag = null;
        BpDepart topDepart = departService.getFatherDepart(SyncConstants.TENENT_ID_DEFAULT, companyCode);
        for(BaseSyncContractorBean bean: list){
            if(bean.getOrgCode() == null || !companyCode.equals(bean.getOrgCode())){
                continue;
            }

            BpContractor contractor = bpContractorDao.findByCodeAndCompanyCode(bean.getCode(),bean.getOrgCode());
            if(contractor == null){
                contractor = new BpContractor();
                contractor.setCode(bean.getCode());
                contractor.setDeleteFlag("0");
                contractor.setState(1);
                contractor.setCompanyName(bean.getName());
                contractor.setRefUrl(bean.getRefUrl());
                contractor.setTenentId(SyncConstants.TENENT_ID_DEFAULT);
                contractor.setOrgCode(bean.getOrgCode());
                contractor.setResponsibleDept(topDepart.getId());
                contractor.setUniqueId(SnowFlakeUtil.getContractorId());
                contractor.setLocateSync(false);
                //是否合格
                if(StringUtils.isEmpty(bean.getFlag())){
                    contractor.setContractorType(SyncConstants.CONTRACT_TYPE_INVALID);
                }else{
                    contractor.setContractorType("1".equalsIgnoreCase(bean.getFlag()) ? SyncConstants.CONTRACT_TYPE_VALID : SyncConstants.CONTRACT_TYPE_INVALID);
                }
                count ++;
                conList.add(contractor);

            }else{
                //修改
                flag =  SyncConstants.CONTRACT_TYPE_VALID.equals(contractor.getContractorType()) ? "1": "0";
                //判断：  contractorType,companyName, refUrl 是否修改
                if(!flag.equals(bean.getFlag()) || !contractor.getCompanyName().equals(bean.getName()) || !contractor.getRefUrl().equals(bean.getRefUrl())){
                    contractor.setCompanyName(bean.getName());
                    contractor.setRefUrl(bean.getRefUrl());
                    if(StringUtils.isEmpty(bean.getFlag())){
                        contractor.setContractorType(SyncConstants.CONTRACT_TYPE_INVALID);
                    }else{
                        contractor.setContractorType("1".equalsIgnoreCase(bean.getFlag()) ? SyncConstants.CONTRACT_TYPE_VALID : SyncConstants.CONTRACT_TYPE_INVALID);
                    }
                    if(StringUtils.isEmpty(contractor.getUniqueId())){
                        contractor.setUniqueId(SnowFlakeUtil.getContractorId());
                    }
                    count ++;
                    conList.add(contractor);
                }
            }
            //批量更新， 每100 个更新一批
            if(conList.size() >=100){
                bpContractorDao.saveAll(conList);
                log.debug(".... 承包商同步Job： 已同步承包商列表 list:{} ....", conList.size());
                orientationDataSyncService.contractor(conList, "saveContractor");
                conList = new ArrayList<>();

            }
        }
        if(conList.size() >0){
            bpContractorDao.saveAll(conList);
            log.debug(".... 承包商同步Job： 已同步承包商列表 list:{} ....", conList.size());
            orientationDataSyncService.contractor(conList, "saveContractor");
        }

        return count;
    }

}
